<template>
  <div class="dashboard-container">
    <!-- 1. 核心数据概览 -->
    <el-card class="stat-card">
      <div slot="header">
        <h4>核心数据概览</h4>
      </div>
      <div class="count-list el-row">
        <div class="el-col el-col-6">
          <div class="count-item">
            <div class="icon-wrapper">
              <i class="el-icon-data-board icon"></i>
            </div>
            <div class="count-info">
              <div class="counts">{{ homeData.dataItemNum || 0 }}</div>
              <div>数据条目总数</div>
            </div>
          </div>
        </div>
        <div class="el-col el-col-6">
          <div class="count-item">
            <div class="icon-wrapper">
              <i class="el-icon-user icon"></i>
            </div>
            <div class="count-info">
              <div class="counts">{{ homeData.userNum || 0 }}</div>
              <div>用户总数</div>
            </div>
          </div>
        </div>
        <div class="el-col el-col-6">
          <div class="count-item">
            <div class="icon-wrapper">
              <i class="el-icon-eye icon"></i>
            </div>
            <div class="count-info">
              <div class="counts">{{ homeData.adShowNum || 0 }}</div>
              <div>广告总曝光</div>
            </div>
          </div>
        </div>
        <div class="el-col el-col-6">
          <div class="count-item">
            <div class="icon-wrapper">
              <i class="el-icon-money icon"></i>
            </div>
            <div class="count-info">
              <div class="counts">¥{{ homeData.totalAdRevenue || 0 }}</div>
              <div>广告总收益</div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 2. 今日待办（管理员视角） -->
    <el-card class="todo-card">
      <div slot="header">
        <h4>今日待办</h4>
      </div>
      <div class="todo-list el-row">
        <div class="el-col el-col-4" v-for="(item, index) in todoItems" :key="index">
          <div class="todo-item">
            <div class="counts">{{ item.count }}</div>
            <div>{{ item.label }}</div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 3. 流量与广告数据 -->
    <el-row :gutter="20" class="flow-row">
      <el-col :span="16">
        <el-card class="flow-card">
          <div slot="header">
            <h4>用户流量分析</h4>
          </div>
          <div class="flow-content">
            <!-- 保留在线模块 -->
            <div class="online-users">
              <div>当前在线用户</div>
              <span>{{ homeData.currentOnline || 0 }}</span>
              <div class="online-tip">较昨日同期 <span :class="homeData.onlineChange > 0 ? 'text-up' : 'text-down'">
                {{ homeData.onlineChange > 0 ? '+' : '' }}{{ homeData.onlineChange }}%
              </span></div>
            </div>
            
            <el-row :gutter="10" class="flow-stats">
              <el-col :span="12">
                <div class="flow-stat-item">
                  <div>今日访客数(UV)</div>
                  <div class="counts">{{ homeData.todayUV || 0 }}</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="flow-stat-item">
                  <div>昨日访客数(UV)</div>
                  <div class="counts">{{ homeData.yesterdayUV || 0 }}</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="flow-stat-item">
                  <div>7日新增用户</div>
                  <div class="counts">{{ homeData.weekNewUser || 0 }}</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="flow-stat-item">
                  <div>广告点击率(CTR)</div>
                  <div class="counts">{{ homeData.adCtr || '0%' }}</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="today-card">
          <div slot="header">
            <h4>今日广告数据</h4>
          </div>
          <div class="today-list">
            <div class="today-item" v-for="(item, index) in todayItems" :key="index">
              <div>{{ item.label }}</div>
              <span :class="item.trend === 'up' ? 'text-up' : item.trend === 'down' ? 'text-down' : ''">
                {{ item.value }}
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 4. 图表分析（广告与用户趋势） -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <div slot="header">
            <h4>近48小时在线用户趋势（整点统计）</h4>
          </div>
          <div id="onlineChart" class="chart-container">
            <div class="chart-placeholder">
              <i class="el-icon-chart"></i>
              <p>在线用户趋势图表（需引入ECharts渲染）</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">
            <h4>广告曝光/点击趋势（近7天）</h4>
          </div>
          <div id="adChart" class="chart-container">
            <div class="chart-placeholder">
              <i class="el-icon-chart"></i>
              <p>广告数据趋势图表（需引入ECharts渲染）</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">
            <h4>广告收益趋势（近7天）</h4>
          </div>
          <div id="revenueChart" class="chart-container">
            <div class="chart-placeholder">
              <i class="el-icon-chart"></i>
              <p>收益趋势图表（需引入ECharts渲染）</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 5. 数据排行榜 -->
    <el-row :gutter="20" class="tables-row">
      <el-col :span="12">
        <el-card class="table-card">
          <div slot="header">
            <h4>热门数据条目TOP10</h4>
          </div>
          <el-table
            stripe
            :columns="hotDataColumns"
            :data="hotDataList"
            border
            :height="300"
          >
            <template slot-scope="scope" slot="action">
              <el-button type="text" size="small" class="operate-btn">编辑</el-button>
              <el-button type="text" size="small" class="operate-btn">查看</el-button>
            </template>
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="table-card">
          <div slot="header">
            <h4>广告位效果TOP10</h4>
          </div>
          <el-table
            stripe
            :columns="adPositionColumns"
            :data="adPositionList"
            border
            :height="300"
          >
            <template slot-scope="scope" slot="action">
              <el-button type="text" size="small" class="operate-btn">配置</el-button>
              <el-button type="text" size="small" class="operate-btn">数据</el-button>
            </template>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'AdBasedDashboard',
  data() {
    // 生成近48小时时间标签
    const generateTimeLabels = () => {
      const labels = [];
      const now = new Date();
      for (let i = 47; i >= 0; i--) {
        const time = new Date(now.getTime() - i * 3600 * 1000);
        labels.push(`${time.getHours()}:00`);
      }
      return labels;
    };

    // 生成模拟数据
    const generateMockData = (length, min, max) => {
      return Array.from({ length }, () => 
        Math.floor(Math.random() * (max - min + 1)) + min
      );
    };

    return {
      // 核心数据（广告为主）
      homeData: {
        dataItemNum: 156,       // 数据条目总数
        userNum: 8923,          // 用户总数
        adShowNum: 125689,      // 广告总曝光
        totalAdRevenue: 3895.6, // 广告总收益
        currentOnline: 156,     // 当前在线用户
        onlineChange: 8,        // 在线用户同比变化
        todayUV: 2356,          // 今日访客数
        yesterdayUV: 1987,      // 昨日访客数
        weekNewUser: 1254,      // 7日新增用户
        adCtr: '3.2%'           // 广告点击率
      },

      // 今日待办（管理员日常操作）
      todoItems: [
        { label: '新增数据条目', count: 5 },
        { label: '更新热门内容', count: 3 },
        { label: '检查广告位', count: 2 },
        { label: '查看收益报表', count: 1 },
        { label: '优化小程序内容', count: 4 },
        { label: '处理用户反馈', count: 2 }
      ],

      // 今日广告核心数据
      todayItems: [
        { label: '今日广告曝光', value: 12568, trend: 'up' },
        { label: '今日广告点击', value: 423, trend: 'up' },
        { label: '今日广告收益', value: '¥289.56', trend: 'up' },
        { label: '新增数据条目', value: 12, trend: 'normal' },
        { label: '小程序访问次数', value: 5689, trend: 'up' },
        { label: '平均停留时长', value: '3:25', trend: 'down' }
      ],

      // 热门数据条目表格配置
      hotDataColumns: [
        { prop: 'rank', label: '排名', width: 80, align: 'center' },
        { prop: 'title', label: '数据标题', minWidth: 180 },
        { prop: 'viewCount', label: '查看次数', width: 120, align: 'center' },
        { prop: 'adShow', label: '广告曝光', width: 120, align: 'center' },
        { prop: 'adClick', label: '广告点击', width: 120, align: 'center' },
        { prop: 'action', label: '操作', width: 140, align: 'center', slot: 'action' }
      ],
      // 热门数据条目模拟数据
      hotDataList: Array.from({ length: 10 }, (_, i) => ({
        rank: i + 1,
        title: `热门数据${i + 1}`,
        viewCount: Math.floor(Math.random() * 5000) + 1000,
        adShow: Math.floor(Math.random() * 3000) + 500,
        adClick: Math.floor(Math.random() * 200) + 20
      })),

      // 广告位效果表格配置
      adPositionColumns: [
        { prop: 'rank', label: '排名', width: 80, align: 'center' },
        { prop: 'position', label: '广告位', minWidth: 120 },
        { prop: 'showCount', label: '曝光量', width: 120, align: 'center' },
        { prop: 'clickCount', label: '点击量', width: 120, align: 'center' },
        { prop: 'ctr', label: '点击率', width: 100, align: 'center' },
        { prop: 'revenue', label: '收益(¥)', width: 120, align: 'center' },
        { prop: 'action', label: '操作', width: 140, align: 'center', slot: 'action' }
      ],
      // 广告位效果模拟数据
      adPositionList: Array.from({ length: 10 }, (_, i) => ({
        rank: i + 1,
        position: `广告位${String.fromCharCode(65 + i)}`, // A, B, C...
        showCount: Math.floor(Math.random() * 10000) + 5000,
        clickCount: Math.floor(Math.random() * 500) + 100,
        ctr: ((Math.random() * 2 + 1)).toFixed(2) + '%',
        revenue: (Math.random() * 500 + 100).toFixed(2)
      })),

      // 图表数据
      chartData: {
        timeLabels: generateTimeLabels(),
        onlineData: generateMockData(48, 50, 300),    // 在线用户数据
        adShowData: generateMockData(7, 8000, 15000), // 广告曝光
        adClickData: generateMockData(7, 200, 800),   // 广告点击
        revenueData: generateMockData(7, 100, 500)    // 收益数据
      }
    };
  },
  methods: {
    // 初始化图表
    initCharts() {
      try {
        const echarts = require('echarts');
        
        // 1. 近48小时在线用户图表
        const onlineChart = echarts.init(document.getElementById('onlineChart'));
        onlineChart.setOption({
          tooltip: { trigger: 'axis' },
          grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
          xAxis: {
            type: 'category',
            data: this.chartData.timeLabels,
            axisLabel: { interval: 3 }
          },
          yAxis: { type: 'value', name: '在线人数' },
          series: [{
            name: '在线用户数',
            type: 'line',
            data: this.chartData.onlineData,
            smooth: true,
            itemStyle: { color: '#409eff' },
            lineStyle: { width: 2 }
          }]
        });

        // 2. 广告曝光/点击趋势图表
        const adChart = echarts.init(document.getElementById('adChart'));
        adChart.setOption({
          tooltip: { trigger: 'axis' },
          legend: { data: ['曝光量', '点击量'], top: 0 },
          grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
          xAxis: {
            type: 'category',
            data: ['7天前', '6天前', '5天前', '4天前', '3天前', '2天前', '昨天'],
          },
          yAxis: [{
            type: 'value',
            name: '曝光量',
            position: 'left',
          }, {
            type: 'value',
            name: '点击量',
            position: 'right',
          }],
          series: [
            {
              name: '曝光量',
              type: 'bar',
              data: this.chartData.adShowData,
              itemStyle: { color: '#67c23a' }
            },
            {
              name: '点击量',
              type: 'line',
              yAxisIndex: 1,
              data: this.chartData.adClickData,
              itemStyle: { color: '#f56c6c' }
            }
          ]
        });

        // 3. 广告收益趋势图表
        const revenueChart = echarts.init(document.getElementById('revenueChart'));
        revenueChart.setOption({
          tooltip: { trigger: 'axis' },
          grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
          xAxis: {
            type: 'category',
            data: ['7天前', '6天前', '5天前', '4天前', '3天前', '2天前', '昨天'],
          },
          yAxis: { type: 'value', name: '收益(¥)' },
          series: [{
            name: '每日收益',
            type: 'line',
            data: this.chartData.revenueData,
            smooth: true,
            itemStyle: { color: '#e6a23c' },
            lineStyle: { width: 2 },
            areaStyle: { color: { type: 'linear', x: 0, y: 0, x2: 0, y2: 1, colorStops: [{ offset: 0, color: 'rgba(230, 162, 60, 0.3)' }, { offset: 1, color: 'rgba(230, 162, 60, 0)' }] } }
          }]
        });

        // 窗口resize适配
        window.addEventListener('resize', () => {
          onlineChart.resize();
          adChart.resize();
          revenueChart.resize();
        });
      } catch (error) {
        console.warn('ECharts初始化失败，请先安装依赖：npm install echarts --save');
      }
    }
  },
  mounted() {
    this.initCharts();
  }
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

// 核心数据概览样式
.stat-card {
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.count-list {
  margin-top: 15px;
}

.count-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 8px;
  color: #fff;
  height: 120px;
  margin: 0 10px;
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  }
}

// 调整数据卡片颜色
.count-item:nth-of-type(1) { background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%); }
.count-item:nth-of-type(2) { background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%); }
.count-item:nth-of-type(3) { background: linear-gradient(135deg, #e6a23c 0%, #f0c179 100%); }
.count-item:nth-of-type(4) { background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%); }

.icon-wrapper {
  margin-right: 15px;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon {
  font-size: 24px;
}

.count-info {
  flex: 1;
}

.counts {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
  letter-spacing: 0.5px;
}

// 今日待办样式
.todo-card {
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.todo-list {
  margin-top: 15px;
}

.todo-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  height: 120px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin: 0 10px;
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.05);
    border-color: #e6f7ff;
  }

  .counts {
    font-size: 28px;
    font-weight: bold;
    color: #409eff;
    margin-bottom: 8px;
  }

  div:last-child {
    color: #666;
    font-size: 14px;
  }
}

// 流量与广告数据样式
.flow-row {
  margin-bottom: 20px;
}

.flow-card, .today-card {
  height: 100%;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.flow-content {
  padding: 15px 0;
}

.online-users {
  text-align: center;
  padding: 25px;
  background-color: #fff;
  border-radius: 8px;
  margin: 0 10px 15px;
  border: 1px solid #f0f0f0;

  div:first-child {
    font-size: 16px;
    color: #666;
    margin-bottom: 12px;
  }

  span {
    font-size: 42px;
    color: #409eff;
    font-weight: bold;
    letter-spacing: 1px;
  }

  .online-tip {
    margin-top: 10px;
    font-size: 14px;
    color: #999;
  }
}

.flow-stats {
  margin: 0 10px;
}

.flow-stat-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  height: 120px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  border: 1px solid #f0f0f0;

  div:first-child {
    color: #666;
    font-size: 14px;
    margin-bottom: 8px;
  }

  .counts {
    font-size: 24px;
    font-weight: bold;
    color: #333;
  }
}

.today-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 5px;
}

.today-item {
  width: 48%;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 12px;
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
    border-color: #e6f7ff;
  }

  div {
    margin-bottom: 8px;
    font-size: 14px;
    color: #666;
  }

  span {
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }
}

.text-up {
  color: #67c23a !important;
}

.text-down {
  color: #f56c6c !important;
}

// 图表区域样式
.charts-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.chart-container {
  height: 320px;
  width: 100%;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  margin-top: 10px;
}

.chart-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;

  i {
    font-size: 32px;
    margin-bottom: 10px;
  }

  p {
    font-size: 14px;
  }
}

// 表格区域样式
.tables-row {
  margin-bottom: 20px;
}

.table-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.el-table {
  margin-top: 15px;
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #fafafa !important;
  font-weight: 500;
  color: #333;
}

.operate-btn {
  color: #409eff !important;
  padding: 0 5px;
}

.operate-btn:hover {
  color: #66b1ff !important;
}
</style>
